package persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class AccesoBD {
	private String driver, url, user, passwd;
	private Connection con;
	private PreparedStatement pstmt;
	private static AccesoBD instance;

	private AccesoBD() throws PersistenciaException{
		
        try {
        	Config conf = Config.getInstancia();
			driver = conf.getArchivoConf("Driver");
	        url = conf.getArchivoConf("Url");
	        user = conf.getArchivoConf("User");
	        passwd = conf.getArchivoConf("Passwd");
        } catch (PersistenciaException e) {
        	throw new PersistenciaException(e.getMessage(),1);
		}
	}
	
	public static AccesoBD getInstance() throws PersistenciaException {
		if (instance == null)
			instance = new AccesoBD();
		return instance;	
	}
	
	public void abrirCon() throws SQLException, ClassNotFoundException{
		Class.forName(driver);
		con = DriverManager.getConnection(url, user, passwd);
	}
	
	//consulta - sin parametros
	public ResultSet execQuery(String query) throws SQLException {
		pstmt = con.prepareStatement(query);
		ResultSet rs = pstmt.executeQuery();
		return rs;		
	}
	
	//consulta - con arreglo de parametros
	public ResultSet execQuery(String query, DataParametros param[]) throws SQLException {
		pstmt = con.prepareStatement(query);
		grabarParametros(param);
		ResultSet rs = pstmt.executeQuery();
		return rs;		
	}
	
	//update - con arreglo de parametros
	public int excecUpdate(String query, DataParametros param[]) throws SQLException {
		pstmt = con.prepareStatement(query);
		grabarParametros(param);
		int rs = pstmt.executeUpdate();
		return rs;	
	}	
	
	
		
	public void cerrarCon() throws SQLException{
		pstmt.close();
		con.close();
	}
	
	//http://stackoverflow.com/questions/3052714/getting-the-count-of-rows-in-a-java-resultset
	public int cantTuplas(ResultSet resultSet) {
	    int size = 0;
	    try {
	        resultSet.last();
	        size = resultSet.getRow();
	        resultSet.beforeFirst();
	    }
	    catch(Exception ex) {
	        return 0;
	    }
	    return size;
	}
	
	private void grabarParametros(DataParametros par[]) throws SQLException{
		for (int i=0; i < par.length; i++){
			switch (par[i].getTipo()){
				case INT:	pstmt.setInt(i+1,(Integer) par[i].getValor());
							break;
				
				case STRING:	pstmt.setString(i+1,(String) par[i].getValor());
								break;
				
				case FLOAT:	pstmt.setFloat(i+1,(Float) par[i].getValor());
							break;
							
				case DATE:	pstmt.setDate(i+1,(java.sql.Date) par[i].getValor());
							break;
				default: break;								
			}
		}
	}
}
